<? include ("../init.php") ?>
<?
	//echo '<pre>';
	//var_dump($_FILES["product_file"]);
	//echo '</pre>';
	
	$fileinfo = explode('.',$_FILES["product_file"]["name"]);
	$fileType = end($fileinfo);
	//$fileFormat = array('csv','xls','xlsx');
	$fileFormat = array('csv');
	
	if(in_array($fileType,$fileFormat))
	{
		$emailfile = $_FILES["product_file"]["tmp_name"];
				
		$row = 1;
		if (($handle = fopen($emailfile, "r")) !== FALSE) {
		
			// $insertdata = '';
			while (($data = fgetcsv($handle, 0 , ",")) !== FALSE) {
				if($row!=1)
				{
					$cid = $db->queryUniqueValue('SELECT c_id FROM hs_category WHERE c_name LIKE "%'.strtolower(trim($data[1])).'%"');
					if($cid==NULL OR $cid==''){
						$cid = 0;
					}
					//echo 'SELECT c_id FROM hs_category WHERE c_name LIKE "%'.strtolower(trim($data[1])).'%"';
					$pid = $db->queryUniqueValue('SELECT p_id FROM hs_product WHERE 	p_style_number="'.strtolower($data[0]).'"');
					if($pid==NULL OR $pid==''){
						$sql = 'INSERT INTO hs_product(c_id,pc_id,p_name,p_detail,p_active,user_allow,p_style_number,p_type,p_metal,p_lenght_inch,p_lenght_mm,p_width_mm) VALUES('.$cid.',0,"","'.utf8_to_tis620((trim(addslashes($data[2])))).'",1,0,"'.utf8_to_tis620(strtolower(trim(addslashes($data[0])))).'","'.utf8_to_tis620(strtolower(trim(addslashes($data[1])))).'","'.utf8_to_tis620(trim(addslashes($data[3]))).'","'.utf8_to_tis620(trim(addslashes($data[4]))).'","'.utf8_to_tis620(trim(addslashes($data[5]))).'","'.utf8_to_tis620(trim(addslashes($data[6]))).'")';
					}else{
						$sql = 'UPDATE hs_product SET c_id="'.$cid.'" , p_detail="'.utf8_to_tis620((trim(addslashes($data[2])))).'",p_style_number="'.utf8_to_tis620(strtolower(trim(addslashes($data[0])))).'",p_type="'.utf8_to_tis620(strtolower(trim(addslashes($data[1])))).'",p_metal="'.utf8_to_tis620(trim(addslashes($data[3]))).'",p_lenght_inch="'.utf8_to_tis620(trim(addslashes($data[4]))).'",p_lenght_mm="'.utf8_to_tis620(trim(addslashes($data[5]))).'",p_width_mm="'.utf8_to_tis620(trim(addslashes($data[6]))).'" WHERE  p_id='.$pid;
					}
					$query = $db->execute($sql);
					//echo $sql.'<br />';
					$query = TRUE;
				}
				$row++;
			}
			fclose($handle);
			
			if($query)
			{
				$statmsg = '<script>alert("Insert products are complete.");</script>';
				$statmsg .= '<script>top.window.location="products.php";</script>';
			}
			else
			{
				$statmsg = '<script>alert("Can\'t insert data, please try agian later.");top.window.location="product_import.php";</script>';
			}
			echo $statmsg;
		}
	}
	else
	{
		echo '<script>alert("Invalid file format, CSV only!!");top.window.location="product_import.php";</script>';
	}
?>